<template>
  <div class="app-container">
    <el-form :model="queryParams" id="selectForm" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="提交时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.submitTimeList"
          type="datetimerange"
          range-separator="至"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm"
          start-placeholder="开始日期"
          size="small"
          @keyup.enter.native="handleQuery"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="提交人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入提交人"
          clearable
          size="small"
          style="width:200px"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option
            v-for="item in dict.type.act_status"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <br>
      <el-form-item label="项目名称" prop="createBy">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          size="small"
          style="width:200px"
        />
      </el-form-item>
      <el-form-item label="项目地点" prop="createBy">
        <el-input  v-if="queryParams.projectAddress" v-model="queryParams.projectAddress" placeholder="请输入项目地点" >
          <i slot="suffix" class="el-icon-close" @click="loadMapQueryParams" style="cursor: pointer;"></i>
        </el-input>
        <el-cascader v-else
                     size="small"
                     :options="options"
                     v-model="selectedOptionsQueryParams"
                     @change="addressChangeQueryParams" clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="采购金额" prop="total" style="margin-left: 10px;">
        <el-input
          v-model="queryParams.purchaseMoneyStart"
          placeholder="请输入"
          clearable
          style="width: 160px"
          @input="queryParams.purchaseMoneyStart=queryParams.purchaseMoneyStart.replace(/^\D*([0-9]\d*\.?\d{0,6})?.*$/,'$1')"
          @keyup.enter.native="handleQuery"
        >
          <i slot="suffix" style="font-style:normal;">万元</i>
        </el-input>
      </el-form-item>
      <el-form-item label="至" prop="total"  label-width="15px">
        <el-input
          v-model="queryParams.purchaseMoneyEnd"
          placeholder="请输入"
          clearable
          style="width: 160px"
          @keyup.enter.native="handleQuery"
          @input="queryParams.purchaseMoneyEnd=queryParams.purchaseMoneyEnd.replace(/^\D*([0-9]\d*\.?\d{0,6})?.*$/,'$1')"
        >
          <i slot="suffix" style="font-style:normal;">万元</i>
        </el-input>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:purchaseApply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oa:purchaseApply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gqdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="提交时间" align="center" prop="actBusinessStatus.createTime" width="180px" sortable/>
      <el-table-column label="提交人" align="center" prop="actBusinessStatus.createBy" width="180px" sortable/>
      <el-table-column label="项目名称" align="center" prop="projectName"  width="180px" sortable/>
      <el-table-column label="项目地点" align="center" prop="projectAddress" width="180px" sortable/>
      <el-table-column label="采购金额（万元）" align="center" prop="total" width="180px" sortable/>
      <el-table-column label="大写" align="center" prop="capitalization" width="180px" sortable/>
      <el-table-column label="流程状态" align="center" prop="actBusinessStatus.status" sortable >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.act_status" :value="scope.row.actBusinessStatus.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.actBusinessStatus.status==='draft'||scope.row.actBusinessStatus.status==='back'||scope.row.actBusinessStatus.status==='cancel'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['oa:purchaseApply:edit']"
          >修改</el-button>
          <el-button
            v-if="(scope.row.actBusinessStatus.status==='draft' || scope.row.actBusinessStatus.status==='cancel' || scope.row.actBusinessStatus.status==='back') && (scope.row.actBusinessStatus.createBy === userId || userId === 'admin' || userId === 'sysadmin')"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['oa:purchaseApply:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status==='waiting'"
            size="mini"
            type="text"
            icon="el-icon-back"
            @click="cancelProcessApply(scope.row)"
          >撤销</el-button>
          <el-button
            v-if="scope.row.actBusinessStatus.status!=='draft' || scope.row.actBusinessStatus.status==='cancel' || scope.row.actBusinessStatus.status==='back'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购申请对话框 -->
    <el-dialog :title="title" width="80%" :visible.sync="open" append-to-body :before-close="cancel">
      <el-tabs  type="border-card" >
        <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" :rules="rules" :inline="true"  class="demo-form-inline">
            <el-form-item label="编号:" prop="number">
              <el-input  v-model="form.number" disabled style="width: 280px;"/>
            </el-form-item>
            <div>
              <el-form-item label="项目名称:" prop="projectName" >
                <el-input v-model="form.projectName" placeholder="请输入项目名称" :disabled='isdisabled' />
              </el-form-item>
              <el-form-item label="项目地点:" prop="projectAddress">
                <el-input :disabled='isdisabled'  v-if="form.projectAddress" v-model="form.projectAddress" placeholder="请输入项目地点" >
                  <i v-if="!isdisabled" slot="suffix" class="el-icon-close" @click="loadMap" style="cursor: pointer;"></i>
                </el-input>
                <el-cascader v-else
                             size="large"
                             :options="options"
                             v-model="selectedOptions"
                             @change="addressChange" clearable>
                </el-cascader>
              </el-form-item>
            </div>
            <el-table ref="table" :data="applyList" style="width: 100%" border>
              <el-table-column label="序号" align="center" width="55" prop="xh" type="index"  >
              </el-table-column>
              <el-table-column prop="itemName" label="物品名称" align="center" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.itemName" :disabled='isdisabled' ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="specificationModel" label="规格型号" align="center" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.specificationModel" :disabled='isdisabled' ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="number" label="数量" align="center" width="140">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.number" :disabled='isdisabled' type="number" @input="scope.row.number=scope.row.number.replace(/\D|^0/g,'')"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="unity" label="单位" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.unity"  @input="scope.row.unity=scope.row.unity.replace(/[^\u4E00-\u9FA5]/g,'')"   :disabled='isdisabled' ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="unitPrice" label="单价（元）" align="center" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.unitPrice" :disabled='isdisabled' @input="scope.row.unitPrice=scope.row.unitPrice.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="totalPrice" label="总价（万元）" align="center" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.totalPrice" disabled ></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="demandDate" label="需求日期" width="250" align="center">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.demandDate"
                    type="datetime"
                    :disabled='isdisabled'
                    format="yyyy-MM-dd HH:mm"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注" width="200" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remarks" :disabled='isdisabled' ></el-input>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="applaydeleteRow(scope.$index, applyList)"
                    :disabled='isdisabled'
                    size="small"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row style="border:0;">
              <el-col style="text-align:center;" ><el-button :disabled='isdisabled' style="border-top:none;width:100px; position: relative;bottom:2px"  @click="applayaddRow(applyList)" >+</el-button></el-col>
            </el-row>
            <el-form-item label="采购金额" prop="total">
              <el-input v-model="form.total" disabled>
                <i slot="suffix" style="font-style:normal;">万元</i>
              </el-input>
            </el-form-item>
            <el-form-item label="大写" prop="capitalization">
              <el-input v-model="form.capitalization" disabled/>
            </el-form-item>
          </el-form>
          <div class="dialog-footer" style="float:right" v-if="flag">
            <el-button :loading="buttonLoading" type="info" @click="submitForm('zancun')">暂存</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')">提交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-tab-pane>
        <!-- 审批历史 -->
        <el-tab-pane label="审批历史" v-if="processInstanceId">
          <history ref="historyRef" :processInstanceId="processInstanceId" ></history>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 提交 -->
    <verify ref="verifyRef" @submitCallback="submitCallback" :taskId="taskId" :taskVariables="taskVariables" :sendMessage="sendMessage"></verify>
  </div>
</template>

<script>
  import {listPurchaseApply,getPurchaseApply,delPurchaseApply,addPurchaseApply,updatePurchaseApply,getProjectList} from "@/api/oa/purchaseApply"
import processApi from "@/api/workflow/processInst";
import history from "@/components/Process/History";
import verify from "@/components/Process/Verify";
import { regionData,CodeToText } from 'element-china-area-data'
  import {parseTime} from "@/utils/ruoyi";
export default {
  name: "purchaseTable",
  dicts: ['act_status'],
  components: {
    history,
    verify
  },
  data() {
    return {
      applyList: [{}],
      tableData1: [], //表单属性
      isdisabled:false,
      bcbtn:true,
      infoId:"",
      xh1:'',
      // 流程实例
      processInstanceId: '',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请表格数据
      gqdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        number: undefined,
        projectName: undefined,
        projectAddress: undefined,
        submitTimeList: [],
        purchaseMoneyStart:'',
        purchaseMoneyEnd:'',
        createBy:'',
        status:''
      },
      // 表单参数
      form: {
        total:0
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键ID不能为空", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        projectAddress: [
          { required: true, message: "项目地点不能为空", trigger: "blur" }
        ],
        total: [
          { required: true, message: "采购金额不能为空", trigger: "blur" }
        ],
        capitalization: [
          { required: true, message: "大写不能为空", trigger: "blur" }
        ],
      },
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {},
      processKey: 'oa_purchase_apply',
      options: regionData,
      selectedOptions: [],
      selectedOptionsQueryParams:[],
      userId:'',
      projectNameList:[],
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.userId=this.$store.state.user.name;
    this.projectNameList();
  },
  watch:{
    'applyList':{
      handler () { //这是vue的规定写法，当你watch的值发生变化的时候，就会触发这个handler，这是vue内部帮你做的事情
        this.form.total=0;
        var regPos = /^[0-9]+.?[0-9]*/;
        this.applyList.map(d   =>{
          if (regPos.test(d.number)&&regPos.test(d.unitPrice)) {
            d.totalPrice = Math.round((Math.round(d.number*100)/100 *Math.round(d.unitPrice*100)/100)*100)/1000000
            this.form.total =Math.round((d.totalPrice + this.form.total)*1000000)/1000000
          }else {
            d.totalPrice=''
          }
        });
        this.form.capitalization=this.digitUppercase(Math.round(this.form.total*1000000)/100);

      },
      deep: true,  // 可以深度检测到 obj 对象的属性值的变化
      immediate: true //刷新加载  立马触发一次handler
    }
  },
  methods: {
    /** 查询采购申请列表 */
    getList() {
      this.loading = true;
      listPurchaseApply(this.queryParams).then(response => {
        this.gqdList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.isdisabled=false
      this.open = false;
      this.applyList=[{}];
      this.selectedOptions=[];
      this.reset();
    },
    loadMap(){
      this.form.projectAddress='';
      this.selectedOptions=[];

    },
    loadMapQueryParams(){
      this.queryParams.projectAddress=''
      this.selectedOptionsQueryParams=[]
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        number: undefined,
        projectName: undefined,
        projectAddress: undefined,
        date: undefined,
        total: undefined,
        capitalization: undefined,
        createTime: undefined,
        updateTime: undefined,
        createBy: undefined,
        updateBy: undefined
      };
      this.processInstanceId = undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams= {
        pageNum: 1,
        pageSize: 10,
        number: undefined,
        projectName: undefined,
        projectAddress: undefined,
        submitTimeList: [],
        purchaseMoneyStart:'',
        purchaseMoneyEnd:'',
        createBy:'',
        status:''
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      if (selection.length==1){
            if (selection[0].actBusinessStatus.status=='draft'||selection[0].actBusinessStatus.status=='back'||selection[0].actBusinessStatus.status=='cancel'){

            }else {
              this.single=true;
            }
      }
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.flag = true
      this.reset();
      this.open = true;
      this.title = "添加采购申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.flag = true
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getPurchaseApply(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if (response.data.actBusinessStatus.createTime){
          this.form.number=this.processKey + '@' + parseTime(response.data.actBusinessStatus.createTime, '{y}{m}{d}{h}{i}{s}')
        }
        if (response.data.purchaseApplyListVoList) {
          this.applyList = response.data.purchaseApplyListVoList;
        }
        this.$nextTick(() => {
          this.processInstanceId=response.data.actBusinessStatus.processInstanceId
        })
        this.open = true;
        this.title = "修改采购申请";
        this.sendMessage = {
          title:'请假申请',
          messageContent:'单据【'+row.id+"】申请"
        }
      });
    },
    //查看
    handleView(row){
      this.flag = false
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getPurchaseApply(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if (response.data.purchaseApplyListVoList) {
          this.applyList = response.data.purchaseApplyListVoList;
        }
        if (response.data.actBusinessStatus.createTime){
          this.form.number=this.processKey + '@' + parseTime(response.data.actBusinessStatus.createTime, '{y}{m}{d}{h}{i}{s}')
        }
        this.$nextTick(() => {
          this.processInstanceId=response.data.actBusinessStatus.processInstanceId
        })
        this.isdisabled=true
        this.open = true;
        this.title = "查看采购申请业务";
      });
    },
    /** 提交按钮 */
    submitForm(flag) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.purchaseApplyListBoList=this.applyList;
          if (this.form.id != null) {
            updatePurchaseApply(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              if(flag === 'submit'){
                this.submitFormApply(response.data)
              }else {
                this.open = false;
              }
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            this.form.purchaseApplyListBoList=this.applyList
            addPurchaseApply(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.cancel();
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 提交成功回调
    submitCallback(){
      this.open = false;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购申请编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delPurchaseApply(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const ids = this.ids;
      this.download('/oa/purchaseApply/export', {
        ...this.queryParams
      }, `purchaseApply_${new Date().getTime()}.xlsx`)
    },
    //提交流程
    submitFormApply(entity){
      let assigneeList = []
      assigneeList.push(1)
      assigneeList.push(2)
      //流程变量
      this.taskVariables = {
        entity: entity,
        userId: '1',
        //assigneeList: assigneeList
      }
      const data = {
        processKey: this.processKey, // key
        businessKey: entity.id, // 业务id
        variables: this.taskVariables,
        classFullName: 'com.ruoyi.oa.domain.OaPurchaseApply'
      }
      // 启动流程
      processApi.startProcessApply(data).then(response => {
        this.taskId = response.data.taskId;
        this.$refs.verifyRef.visible = true
        this.$refs.verifyRef.reset()
      })
    },
    //撤回
    cancelProcessApply(row){
      this.$modal.confirm('是否撤销申请').then(() => {
        this.loading = true;
        return processApi.cancelProcessApply(row.actBusinessStatus.processInstanceId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    //添加表格里的行(申请状态)
    applayaddRow(tableData1) {
      tableData1.push({
        specificationModel: "",
        number: "",
        unity: "",
        unitPrice: "",
        totalPrice:'',
        demandDate:'',
        remarks:'',
        xh:this.xh1,
        infoId:this.infoId
      });

    },
    //删除表格里的行(申请状态)
    applaydeleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 金额数字转大写
    digitUppercase(price) {
      const fraction = ['角', '分']
      const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      const unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ]
      let num = Math.abs(price)
      let s = ''
      fraction.forEach((item, index) => {
        s += (digit[Math.floor(num * 10 * (10 ** index)) % 10] + item).replace(/零./, '')
      })
      s = s || '整'
      num = Math.floor(num)
      for (let i = 0; i < unit[0].length && num > 0; i += 1) {
        let p = ''
        for (let j = 0; j < unit[1].length && num > 0; j += 1) {
          p = digit[num % 10] + unit[1][j] + p
          num = Math.floor(num / 10)
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
      }

      return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
    },
    addressChange(arr) {
      this.form.projectAddress=CodeToText[arr[0]]+'->'+CodeToText[arr[1]]+'->'+CodeToText[arr[2]]
      this.selectedOptions=[];
    },
    addressChangeQueryParams(arr) {
      this.queryParams.projectAddress=CodeToText[arr[0]]+'->'+CodeToText[arr[1]]+'->'+CodeToText[arr[2]]
      this.selectedOptionsQueryParams=[];
    },
    projectNameList(){
      getProjectList().then(res=>{
        this.projectNameList=res.data
      })
    }
  }
};
</script>

<style scoped>
/* 设置滚动条宽度和高度 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px; /* 横向滚动条 */
  height: 8px; /* 纵向滚动条 必写 */
}
/* 设置滚动条样式 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #dde;
  border-radius: 3px;
}
#selectForm >>> .el-form-item__label {
  font-size: 12px;
}
</style>
